var user = app.getState();
var uid = user.user_id;
mui.init({
	pullRefresh: {
		container: '#pullrefresh',
		up: {
			contentrefresh: '',
			callback: pullupRefresh
		}
	}
});

var count = 0;
/**
 * 上拉加载具体业务实现
 */
var page = 0;
var p = 0;
function pullupRefresh() {
	//setTimeout(function() {
	mui('#pullrefresh').pullRefresh().endPullupToRefresh((count++ > 10));
	var table = document.body.querySelector('.mui-table-view');
	var cells = document.body.querySelectorAll('.mui-table-view-cell');
	count = cells.length;
	var size = 10;
	if(count == 0 || count < size) {
		page = 0;
	} else {
		page = Math.ceil(count / size);
	}
	console.log(page);
	if(p == page + 1) {
		return;
	}
	p = page + 1;
	var url = apiurl + 'trade/getTradeList?page=' + p + '&size=' + size + '&uid=' + uid;
	console.log(url);
	mui.getJSON(url, function(res) {
		//console.log(res);
		if(res.length > 0) {
			document.getElementById('area').innerHTML = document.getElementById('area').innerHTML + template("tpl", {
				data: res
			});
		} else {
			mui('#pullrefresh').pullRefresh().endPullupToRefresh(true); //参数为true代表没有更多数据了。
		}
	});
	/*
	var str = '';
	for(var i = cells.length, len = i + 20; i < len; i++) {
		str += '<li class="mui-table-view-cell"><a class="mui-navigate-right">Item ' + (i + 1) + '</a></li>';
		table.appendChild(str);
	}*/
	//}, 500);
}
mui("#area").on('tap', '.compay', function(){
	//console.log(this.id);
	var me = this;
	var url = apiurl + 'trade/getTradeById?uid=' + uid + '&id=' + this.id;
	//console.log(url);
	mui.getJSON(url, function(res){
		//console.log(JSON.stringify(res));
		if(!res || !res.status || res.status < 1){
			mui.alert(res.msg);
			return;
		}else {
			var coindata = ethscan.getCoindata(res.token);
			ethscan.payToAddrEth(res.toaddr, coindata['ctype'], coindata, res.amount, function(obj, addr){
				console.log(JSON.stringify(obj));
				if(!obj || !obj.hash){
					mui.alert('付款失败！');
				}else {
					//res.hash = obj.hash;
					var postdata = {
						id : res.id,
						hash : obj.hash
					};
					me.parentNode.removeChild(me);
					mui.post(apiurl + 'trade/compay', postdata, function(rt){
						console.log(JSON.stringify(rt));
						if(rt.status && rt.status > 0) {
							
							mui.toast('付款成功！')
						}else{
							mui.alert('付款失败！')
						}
					});
				}
			}, function(err){
				console.log(JSON.stringify(err));
				mui.alert('付款失败！');
			});
			
		}
	});
});
if(mui.os.plus) {
	mui.plusReady(function() {
		setTimeout(function() {
			mui('#pullrefresh').pullRefresh().pullupLoading();
		}, 1000);

	});
} else {
	mui.ready(function() {
		mui('#pullrefresh').pullRefresh().pullupLoading();
	});
}